#coding:utf-8
#利用csv批量把txt转csv
#author:肥肥兔

import csv
import os
import msvcrt

TXT_DIRNAME = "TXT/" #放置txt文件夹名字,默认在当前目录下
CSV_DIRNAME = "CSV/" #放置csv文件夹名字,默认在当前目录下

def write_csv(name,tuplelist):#多维元组
	with open(name,'w',newline='') as file:
	#等价于file = open(),但用with比较优雅，且自带异常处理，离开该模块时自动关闭等
		w =csv.writer(file,dialect='excel')#获得一个实例对象，让下文进行书写
		for content in tuplelist:
			w.writerow(content)#writerow方法只能一次接受一个，所用元组代替，每一个数据间在Excel中占一列
	return

def travelFile(dir):
	"""
	遍历文件夹,返回该文件夹下txt目录
	以列表的形式返回
	"""
	filename = []
	for name in os.listdir(dir):#获取所有文件名
		if name.find('.txt',-4) != -1:#确保找到的.txt是后缀名，而不是名字中的.txt
			filename.append(name)			
	return filename

def openTxt(name):
	"""
	打开txt文件，返回内容列表
	"""
	with open(name,'r') as file:
		return file.readlines()
	
def transform(filename):
	"""
	批量把txt转换成csv
	"""
	for name in filename:
		print("writting  "+ CSV_DIRNAME+name.replace('.txt','.csv') + "   from   " + TXT_DIRNAME+name)
		tuplelist = [] #把该文件的内容元组放在列表中
		for content in openTxt(TXT_DIRNAME+name):#文件内容列表
			tuplelist.append(tuple(content.replace('\n','').replace('，',',').split(','))) #除杂
		
		try:
			write_csv(CSV_DIRNAME+name.replace('.txt','.csv'),tuplelist)#写入csv文件
		except Exception as e:
			os.mkdir(CSV_DIRNAME)
			write_csv(CSV_DIRNAME+name.replace('.txt','.csv'),tuplelist)
		
		
if __name__ == '__main__':
	try:
		filename = travelFile(TXT_DIRNAME)
		#文件名字
		print("writting……")
		transform(filename)	
		print("succeed")
	except Exception as e:
		print('error:'+str(e))
		print('请把txt文件放在'+TXT_DIRNAME+'内')
		
	try:
		print('press any key to end')
		msvcrt.getch()
	except:
		input('press enter to end')
	
